using RestSharp;
using Nett;
using System;
using System.Threading;
using System.IO;
// string logFilePath = "logfile.txt";
// using (StreamWriter writer = new StreamWriter(logFilePath));


namespace RestSharpHttp
{
    class RestPost
    {

        public static string AutoLogin(string UserName, string  UserPwd )
        {
            try
            {
                var options = new RestClientOptions("https://1.1.1.2:444");
                // 允许不安全的HTTPS
                options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                var client = new RestClient(options);
                var request = new RestRequest("/ac_portal/login.php", Method.Post);
                // 定义POST的数据为一个字典
                var dataDict = new Dictionary<string, string>()
                { {"opr", "pwdLogin"}, {"userName", UserName}, {"pwd", UserPwd}, {"rememberPwd", "0"} };
                request.Timeout = 5000;
                // 定义Headers
                request.AddHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8");
                // 遍历字典数值添加到request表单
                foreach (var item in dataDict)
                {
                    // Console.WriteLine(item.Key + ": " + item.Value);
                    request.AddParameter(item.Key, item.Value);
                }
                RestResponse response = client.Execute(request);
                // Console.WriteLine($"返回状态：{Convert.ToInt32(response.StatusCode)}");
                Console.WriteLine("response: " + response.IsSuccessful.ToString());
                if (response.IsSuccessful && response.Content != null)
                {
                    // Console.WriteLine(response.Content.ToString());
                    return response.Content.ToString();
                }
                else
                {
                    return "请求失败";
                }

            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        public static bool CheckOnline()
        {
            try
            {
                var options = new RestClientOptions("https://baidu.com");
                var client = new RestClient(options);
                var request = new RestRequest("/", Method.Get);
                request.Timeout = 5000;
                RestResponse response = client.Execute(request);
                // Console.WriteLine($"返回状态：{Convert.ToInt32(response.StatusCode)}");
                if (Convert.ToInt32(response.StatusCode) == 302 && response.Content != null)
                {
                    Console.WriteLine($"已经连接Internet!");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        class RunClass
        {
            public static void WaitFunctions(int waitTime)
            {
                if (waitTime <= 0) return;


                DateTime nowTimer = DateTime.Now;
                int interval = 0;
                while (interval < waitTime)
                {
                    Console.WriteLine($"{waitTime - interval}秒后再次启动检查 ...");
                    Thread.Sleep(5000);
                    TimeSpan spand = DateTime.Now - nowTimer;
                    interval = spand.Seconds;
                    // Console.WriteLine($"{waitTime - interval}秒再次启动检查 ...");
                }

            }
            static void Main(string[] args)
            {
                string filePath = "auto_login_config.toml";
                if (!File.Exists(filePath))
                {
                    Console.WriteLine($"配置文件{filePath}在程序所在目录下不存在!");
                    Thread.Sleep(3000);
                    return;
                }
                // 读取TOML文件
                TomlTable table = Toml.ReadFile("auto_login_config.toml");
                // 获取TOML文件中的值
                string UserName = table.Get<string>("userName");
                string UserPwd = table.Get<string>("password");
                int check_span = table.Get<int>("check_span");
                bool run_background = table.Get<bool>("run_background");
                RestPost rest = new();
                bool Continue_Flag = true;
                while (Continue_Flag || run_background)
                {
                    Console.WriteLine($"开始检查是否连接到Internet!");
                    bool isOnline = CheckOnline();
                    if (!isOnline)
                    {
                        string ret = AutoLogin(UserName, UserPwd);
                        Console.WriteLine(ret);
                        WaitFunctions(check_span);
                        Console.Clear();
                    }
                    else {
                        Continue_Flag = false;
                    }
                    Thread.Sleep(3000);
                }

                // WaitFunctions(4);
                // Console.WriteLine($"5秒后自动退出...");
                // Thread.Sleep(5000);
                // Console.ReadKey();
            }
        }
    }
}
